package com.xdja.study.http;

import com.xdja.study.AppConfiguration;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.MalformedURLException;
import java.net.URL;

@Component
public class HttpClientVerticle extends AbstractVerticle {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private AppConfiguration appConfiguration;
    private HttpClient httpClient;
    @Override
    public void start() throws MalformedURLException {
        httpClient = vertx.createHttpClient(
                new HttpClientOptions().setSsl(false)
                        .setVerifyHost(false).
                        setTrustAll(true).setKeepAlive(true)
                        .setConnectTimeout(2000)
                        .setIdleTimeout(10).setMaxWaitQueueSize(500).setMaxPoolSize(1000));


        final URL url = new URL(appConfiguration.httpUrl());
        vertx.eventBus().consumer("http.client", message -> {
            httpClient.getNow(url.getPort(), url.getHost(), url.getFile() , resp -> {

                if(resp.statusCode() != 200) {
                    logger.error("调用Http失败, statusCode:{}", resp.statusCode());
                    throw new RuntimeException("调用Http失败");
                }
                resp.exceptionHandler(throwable -> {
                    logger.error("调用http返回出现异常:{}", throwable.getMessage() );
                    throw new RuntimeException("调用http返回出现异常");
                });
                resp.bodyHandler(body -> {
                    message.reply(new JsonObject().put("info", body.toString("UTF-8")));
                });
            });

        });
    }
}
